import { Form, InputNumber, message, Space, Spin } from 'antd';
import { useEffect, useState } from 'react';
// import { useModel } from 'umi';
import { ModalForm, ProFormTextArea } from '@ant-design/pro-form';
import RemoteSelect from '../../components/RemoteSelect';
import { getLogisticsOptions } from '../../config/service';
import { logisticsSearchDetail, updateLogisticsSearch } from '../service';
// import { createSearchType } from '../data';

interface undateParkList {
  visible: boolean;
  unVisible: () => void;
  reloadFunc: () => void;
  id: string;
}

export default (props: undateParkList) => {
  const { visible, unVisible, reloadFunc, id } = props;

  const [initialList, setInitialList] = useState<number[]>();
  const [priceArray, setPriceArray] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [chargeType, setChargeType] = useState<boolean>(false);
  const [weightPrice, setWeightPrice] = useState<number[]>([]);
  const [form] = Form.useForm();

  useEffect(() => {
    logisticsSearchDetail(id).then(async (e) => {
      if (e.data._doc.logisticsConfig) {
        const res = await getLogisticsOptions({ _id: e.data._doc.logisticsConfig.id });
        if (res.data[0]._doc.chargeType == 2) {
          setChargeType(true);
        } else {
          setChargeType(false);
        }
        setInitialList(
          [res.data[0]._doc.startingWeight, res.data[0]._doc.weightInterval].flat(Infinity),
        );
        const Price: string[] = [];
        if (res.data[0]._doc.startingWeight != 0) {
          Price.push(`首重${res.data[0]._doc.startingWeight}kg`);
          Price.push(
            `${res.data[0]._doc.startingWeight}kg-${res.data[0]._doc.weightInterval[0]}kg`,
          );
          for (let i = 0; i < res.data[0]._doc.weightInterval.length; i++) {
            if (i == res.data[0]._doc.weightInterval.length - 1) {
              Price.push(`${res.data[0]._doc.weightInterval[i]}kg-∞`);
            } else {
              Price.push(
                `${res.data[0]._doc.weightInterval[i]}-${res.data[0]._doc.weightInterval[i + 1]}kg`,
              );
            }
          }
        } else {
          Price.push(`0kg-${res.data[0]._doc.weightInterval[0]}kg`);
          for (let i = 0; i < res.data[0]._doc.weightInterval.length; i++) {
            if (i == res.data[0]._doc.weightInterval.length - 1) {
              Price.push(`${res.data[0]._doc.weightInterval[i]}kg-∞`);
            } else {
              Price.push(
                `${res.data[0]._doc.weightInterval[i]}-${res.data[0]._doc.weightInterval[i + 1]}kg`,
              );
            }
          }
        }
        let areaSum = '';

        e.data._doc?.area.map((item: string) => {
          areaSum += item + '/';
        });
        if (areaSum.endsWith('/')) {
          areaSum = areaSum.substring(0, areaSum.length - 1);
        }

        setPriceArray(Price);
        setWeightPrice(e.data._doc.weightPrice);
        form.setFieldsValue({
          logisticsName: {
            id: e.data._doc.logisticsConfig.id,
            logisticsName: e.data._doc.logisticsConfig.name,
          },
          lowCharge: e.data._doc.lowCharge / 100,
          weightPrice: e.data._doc.weightPrice,
          area: areaSum,
        });
      }
      setLoading(false);
    });
  }, []);
  return (
    <div>
      <ModalForm
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            unVisible();
          },
          centered: true,
          footer: null,
        }}
        onFinish={async (value: any) => {
          const regex = /^[\u4E00-\u9FA5]{2,14}$/;
          const area = [];
          if (value.area.includes(',')) {
            value.area.split(',');
            for (let i = 0; i < value.area.split(',').length; i++) {
              if (!regex.test(value.area.split(',')[i])) {
                message.info('地区汉字只能为2-14格');
                return false;
              } else {
                area.push(value.area.split(',')[i]);
              }
            }
          } else if (value.area.includes('/')) {
            value.area.split('/');
            for (let i = 0; i < value.area.split('/').length; i++) {
              if (!regex.test(value.area.split('/')[i])) {
                message.info('地区汉字只能为2-14格');
                return false;
              } else {
                area.push(value.area.split('/')[i]);
              }
            }
          } else if (value.area.includes('、')) {
            value.area.split('、');
            for (let i = 0; i < value.area.split('、').length; i++) {
              if (!regex.test(value.area.split('、')[i])) {
                message.info('地区汉字只能为2-14格');
                return false;
              } else {
                area.push(value.area.split('、')[i]);
              }
            }
          } else if (value.area.includes('，')) {
            value.area.split('，');
            for (let i = 0; i < value.area.split('，').length; i++) {
              if (!regex.test(value.area.split('，')[i])) {
                message.info('间隔符间内容不为2-14字数的汉字');
                return false;
              } else {
                area.push(value.area.split('，')[i]);
              }
            }
          } else {
            if (!regex.test(value.area)) {
              message.info('地区汉字只能为2-14格');
              return false;
            } else {
              area.push(value.area);
            }
          }
          const values = {
            _id: id,
            area: area,
            logisticsConfig: {
              id: value.logisticsName.id,
              name: value.logisticsName.logisticsName,
            },
            lowCharge: value.lowCharge * 100,
            weightPrice: value.weightPrice.map((item: { price: number }) => {
              return item.price * 100;
            }),
          };
          const hide = message.loading('正在更新');
          const res = await updateLogisticsSearch(values);
          hide();
          if (res.code === 0) {
            message.success(`更新成功`);
            reloadFunc();
            unVisible();
            return true;
          } else {
            message.error(`更新失败,${res.message}`);
            return false;
          }
        }}
        layout="horizontal"
        visible={visible}
        title="更新物流信息"
        width={850}
        form={form}
      >
        <Spin spinning={loading}>
          <Form.Item label="配置选择" name="logisticsName" required>
            <RemoteSelect
              disabled
              getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
              fieldNames={{ key: 'id', value: 'id', label: 'logisticsName' }}
              request={(search) => getLogisticsOptions({ logisticsOption: search })}
            />
          </Form.Item>
          {initialList && (
            <ProFormTextArea
              fieldProps={{
                showCount: true,
                maxLength: 30,
                style: { height: '30px' },
              }}
              required
              label="目的地"
              placeholder="示例：天津、北京、石家庄、吉林 | 西安\南昌\武汉\贵州 | 长沙,厦门,广州,杭州"
              name="area"
            />
          )}
          {chargeType && (
            <Form.Item label="最低收费" required name="lowCharge">
              <InputNumber addonAfter="元" min={0} precision={2} />
            </Form.Item>
          )}
          {initialList && (
            <div>
              <Form.List name="weightPrice">
                {(fields, {}) => (
                  <>
                    {fields.map((field, index) => (
                      <Space key={field.key + 1} align={'baseline'} size={0}>
                        <Form.Item
                          {...field}
                          name={field.name}
                          label={`重量区间${index + 1}`}
                          key={`week${index + 1}`}
                          rules={[{ required: true, message: `请输入休眠时段${index + 1}` }]}
                        >
                          <Form.Item
                            {...field}
                            rules={[{ required: true, message: '' }]}
                            name={[field.name, 'price']}
                            noStyle
                            initialValue={weightPrice[index] / 100}
                          >
                            <InputNumber
                              style={{ marginRight: 14, width: 256 }}
                              addonAfter={'元'}
                              addonBefore={priceArray[index]}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Space>
                    ))}
                  </>
                )}
              </Form.List>
            </div>
          )}
        </Spin>
      </ModalForm>
    </div>
  );
};
